# coding: utf-8
import re
from itertools import groupby
from difflib import get_close_matches

def parse_sql_script(sql_script, table_name):
    tables = re.findall(fr'CREATE TABLE\s+{table_name}\s+\((.*?)\);', sql_script, re.DOTALL)
    columns = []
    for table in tables:
        for column in map(str.strip, table.split(',')):
            if not column:
                continue
            if 'PRIMARY' not in column or\
               'CONSTRAINT' not in column or \
               'INDEX' not in column:
                column_name = re.search(r'(\w+)', column).group(1)
                columns.append(column_name)
        return columns

def get_lm_cols(data, table_name):
    cols = data.get(table_name, None)
    if not cols:
        return []
    return [col.strip().split('\t')[0] for col in cols]

        
with open('merge.txt','rt') as mgp, \
     open('sd2.sql', 'rt') as sdp, \
     open('table_maps.txt', 'rt') as lmp, \
     open('sd_table_maps.txt', 'wt') as tmp:
    sd2_data = sdp.read()
    lm_data = [list(v) for _, v in groupby(lmp, key=lambda x: x.startswith('\t'))]
    lm_data = { t[0].strip().split('\t')[0]: c for t, c in zip(lm_data[::2], lm_data[1::2])}
    for table in mgp:
        lm, sd2  = table.strip().split(' ')
        sd2_cols = parse_sql_script(sd2_data, sd2)
        if not sd2_cols:
            continue
        lm_cols = get_lm_cols(lm_data, lm)
        print(lm, sd2, sep='\t', file = tmp)
        for lm_col in lm_cols:
            sd_col = get_close_matches(lm_col, sd2_cols)
            if sd_col:
                print('\t', lm_col, sd_col[0], sep='\t', file = tmp)
        
        
        
